// stores/permission.js
import { defineStore } from 'pinia'
import { authRoutes } from '@/router/routes'

export const usePermissionStore = defineStore('permission', {
  state: () => ({
    routes: [],
    isReady: false // 新增路由就绪状态
  }),

  actions: {
    async generateRoutes(roles) {
      try {
        if (this.hasGenerated) return
        
        // 深度过滤路由
        const filterRoutes = (routes) => {
          return routes.filter(route => {
            const hasPermission = !route.meta?.roles || 
                route.meta.roles.some(r => roles.includes(r))
            const validChildren = route.children?.length ? 
                filterRoutes(route.children) : []
            return hasPermission && !route.meta?.hidden && 
                (validChildren.length || route.component)
          })
        }
        
        this.routes = filterRoutes(authRoutes)
        this.hasGenerated = true
      } catch (error) {
        console.error('路由生成失败:', error)
      }
    }
  }
})
